<script setup lang="ts" name="building-list">
import {
useReformInstallationProjectUnitList,
useReformInstallationProjectUnitSave,
} from "@fl/api/elevator-api";
import { SearchTable, SubmitBtn } from "@fl/components";
import { useMessage } from "@fl/hooks/web/use-message";
import { hasPermi } from "@fl/utils/has-permi";
import { cloneDeep } from "lodash-es";
import type { PlusDialog } from "plus-pro-components";
import { useRoute, useRouter } from "vue-router";
import type { VxeGridProps } from "vxe-table";

const { createConfirmModal } = useMessage();
const route = useRoute();
const { go } = useRouter();
const projectName = route.query.projectName as string | undefined;
const buildingId = route.query.buildingId as string | undefined;
const buildingName = route.query.buildingName as string | undefined;
const natureNo = route.query.natureNo as string | undefined;
const initForm = {
    building: "",
    natureNo: "",
    unit: "",
    unitNo: "",
};
const form = ref(cloneDeep(initForm));
const initialState = {
    buildingId: buildingId || "",
};
const visible = ref(false);

const state = ref(cloneDeep(initialState));
// const tablePage = reactive({
//     currentPage: 1,
//     pageSize: 10,
//     total: 0,
// });
const params = computed(() => ({
    ...state.value,
    // pageIndex: tablePage.currentPage,
    // pageSize: tablePage.pageSize,
    orderBy: "create_time", // 根据创建时间排序
    orderType: "desc", // 降序
}));
const { data, isLoading } = useReformInstallationProjectUnitList(params);
const records = ref<any>();

// const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
//     tablePage.currentPage = currentPage;
//     tablePage.pageSize = pageSize;
// };
watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value);
    }
});

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: "序号", type: "seq", width: 60 },
        { field: "building", title: "楼栋" },
        { field: "natureNo", title: "自然栋号" },
        { field: "unit", title: "单元名称" },
        { field: "unitNo", title: "单元号" },
        { slots: { default: "operate" }, title: "操作", width: 150 },
    ],
});

const formRef = ref();
function goBack() {
    go(-1);
}
watch(
    () => visible.value,
    () => {
        if (visible.value) {
            form.value.building = buildingName || "";
            form.value.natureNo = natureNo || "";
        }
    }
);
function cancel() {
    createConfirmModal({
        title: "提示",
        content: "您是否确定要放弃当前已编辑或输入的信息?",
        onSuccess: () => {
            reset();
        },
    });
}

function reset() {
    form.value = cloneDeep(initForm);
    visible.value = false;
}

const rules = {
    building: [{ required: true, message: "请输入楼栋名称", trigger: "blur" }],
    natureNo: [{ required: true, message: "请输入自然栋编号", trigger: "blur" }],
    unit: [{ required: true, message: "请输入单元名称", trigger: "blur" }],
    // unitNo: [{ required: true, message: "请输入单元号", trigger: "blur" }],
};

const { mutate, isPending } = useReformInstallationProjectUnitSave();
function submit() {
    formRef.value.validate((valid) => {
        let params = {
            ...form.value,
            buildingId: buildingId,
        };
        if (valid) {
            createConfirmModal({
                title: "保存",
                content: "确定保存吗？",
                onSuccess: () => {
                    mutate(params, {
                        onSuccess: () => {
                            ElMessage.success("保存成功");
                            reset();
                        },
                    });
                },
            });
        }
    });
}
const title = ref("新增");
function showDialog(type: string, row?: any) {
    if (type === "detail" || type === "edit") {
        title.value = type === "detail" ? "查看" : "编辑";
        form.value = cloneDeep(row);
        console.log(form.value);
        visible.value = true;
    } else {
        title.value = "新增";
        visible.value = true;
    }
}
function unitNoBlur() {
    const pattern = /^[A-Za-z0-9]+$/;
    if (!pattern.test(form.value.unitNo)) {
        form.value.unitNo = initForm.unitNo;
    }
}
function unitNoInput() {
    const pattern = /^[A-Za-z0-9]+$/;
    if (!pattern.test(form.value.unitNo)) {
        ElMessage.warning("单元只能包含字母或者数字");
    }
}
</script>
<template>
    <ElCard shadow="never">
        <div class="flex items-center">
            <div @click="go(-1)" class="hoverRed">{{ projectName }}</div>
            <div class="px-8">/</div>
            <div>
                {{ buildingName }}
            </div>
        <el-button @click="goBack" class="ml-16"> 返回楼栋 </el-button>
        </div>
        
        <ElSkeleton v-if="isLoading" animated class="mt-20" />
        <template v-else>
            <SearchTable v-bind="gridOptions" :loading="isLoading" :data="records">
                <template #toolbar_buttons>
                    <ElButton
                        type="primary"
                        @click="showDialog('add')"
                        v-if="hasPermi('清册数据-新增楼栋')"
                        >新增</ElButton
                    >
                </template>
                <template #operate="{ row }">
                    <ElButton
                        text
                        type="primary"
                        @click="showDialog('edit', row)"
                        v-if="hasPermi('清册数据-新增楼栋')"
                        >编辑</ElButton
                    >
                </template>
            </SearchTable>
        </template>
    </ElCard>
    <PlusDialog
        v-model="visible"
        :title="title"
        width="800"
        close-on-press-escape
        :has-footer="false"
        @closed="reset"
    >
        <template v-if="title != '查看'">
            <div class="formBox">
                <el-form ref="formRef" :model="form" label-width="auto" :rules="rules">
                    <el-row :gutter="40">
                        <el-col :span="24">
                            <el-form-item label="楼栋" prop="building">
                                <el-input
                                    v-model="form.building"
                                    placeholder="请输入楼栋名称"
                                    disabled
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="自然栋栋号" prop="natureNo">
                                <el-input
                                    v-model="form.natureNo"
                                    placeholder="请输入自然栋栋号"
                                    disabled
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="单元名称" prop="unit">
                                <el-input
                                    v-model="form.unit"
                                    placeholder="请输入单元名称"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="单元号" prop="unitNo">
                                <el-input
                                    v-model="form.unitNo"
                                    placeholder="请输入单元号"
                                    @blur="unitNoBlur"
                                    @input="unitNoInput"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="mx-auto mt20 flex justify-center">
                <el-button @click="cancel"> 取消 </el-button>

                <SubmitBtn type="primary" :loading="isPending" @click="submit">
                    保存
                </SubmitBtn>
            </div>
        </template>
        <template v-else>
            <div class="formBox">
                <el-form :model="form" label-width="auto">
                    <el-row :gutter="40">
                        <el-col :span="24">
                            <el-form-item label="楼栋:" prop="building">
                                {{ form.building || "" }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="自然栋号:" prop="natureNo">
                                {{ form.natureNo || "" }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="单元名称:" prop="unit">
                                {{ form.unit || "" }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="单元号:" prop="unitNo">
                                {{ form.unitNo || "" }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </template>
    </PlusDialog>
</template>
<style lang="scss" scoped>
.formBox {
    // height: 500px;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 8px;
    width: 100%;
    &::-webkit-scrollbar {
        width: 4px;
    }

    /* 自定义滚动条的滑块（thumb） */
    &::-webkit-scrollbar-thumb {
        background: #dcdfe6;
        border-radius: 2px;
    }
}
.hoverRed {
    font-weight: 600;
    color: #303133;
    cursor: pointer;
}
.hoverRed:hover {
    color: #da0004 !important;
}
</style>
